/*
 * Copyright (C) 2025 Thomas Akehurst
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.github.tomakehurst.wiremock.db.service;

import com.github.tomakehurst.wiremock.common.Json;
import com.github.tomakehurst.wiremock.db.entity.StubMappingEntity;
import com.github.tomakehurst.wiremock.db.mapper.StubMappingMapper;
import com.github.tomakehurst.wiremock.stubbing.StubMapping;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

public class StubMappingService {
  private final SqlSessionFactory sqlSessionFactory;

  public StubMappingService(SqlSessionFactory sqlSessionFactory) {
    this.sqlSessionFactory = sqlSessionFactory;
  }

  // 保存单个存根（新增或更新）
  public void save(StubMapping stubMapping) {
    try (SqlSession session = sqlSessionFactory.openSession(true)) { // 自动提交事务
      StubMappingMapper mapper = session.getMapper(StubMappingMapper.class);
      StubMappingEntity entity = toEntity(stubMapping);

      // 若已存在则更新，否则新增
      if (mapper.findById(entity.getId()) != null) {
        entity.setUpdatedAt(LocalDateTime.now());
        mapper.update(entity);
      } else {
        entity.setCreatedAt(LocalDateTime.now());
        entity.setUpdatedAt(LocalDateTime.now());
        mapper.insert(entity);
      }
    }
  }

  // 批量保存存根
  public void saveAll(List<StubMapping> stubMappings) {
    stubMappings.forEach(this::save);
  }

  // 根据ID删除
  public void deleteById(UUID id) {
    try (SqlSession session = sqlSessionFactory.openSession(true)) {
      StubMappingMapper mapper = session.getMapper(StubMappingMapper.class);
      mapper.deleteById(id.toString());
    }
  }

  // 删除所有单存根
  public void deleteAll() {
    try (SqlSession session = sqlSessionFactory.openSession(true)) {
      StubMappingMapper mapper = session.getMapper(StubMappingMapper.class);
      mapper.deleteAll();
    }
  }

  // 查询所有单存根
  public List<StubMapping> findAll() {
    try (SqlSession session = sqlSessionFactory.openSession()) {
      StubMappingMapper mapper = session.getMapper(StubMappingMapper.class);
      return mapper.findAll().stream()
          .map(StubMappingEntity::toStubMapping)
          .collect(Collectors.toList());
    }
  }

  // 转换 StubMapping -> StubMappingEntity
  private StubMappingEntity toEntity(StubMapping stubMapping) {
    StubMappingEntity entity = new StubMappingEntity();
    entity.setId(stubMapping.getId().toString());
    entity.setContent(Json.writePrivate(stubMapping)); // 使用WireMock的JSON工具序列化
    entity.setIsPersistent(stubMapping.shouldBePersisted());
    // 补充其他字段（如sanitizedUrl可从请求URL提取，originalFilename为null）
    entity.setSanitizedUrl(stubMapping.getRequest().getUrl());
    return entity;
  }
}
